package com.dbapp.garden.controller.sys;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import com.dbapp.garden.config.security.PermissionUser;
import com.dbapp.garden.config.security.PermissionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dbapp.garden.entity.SysResource;
import com.dbapp.garden.service.SysResourceService;
import com.dbapp.garden.vo.Tree;
import org.springframework.web.bind.annotation.SessionAttribute;

/**
 * 资源管理的控制器类
 * 
 * @author gangzi
 *
 */

@Controller
public class SysResourceController {

	@Autowired
	private SysResourceService sysResourceService;

	@GetMapping("/getAllTreeData")
	@ResponseBody
	public List<Tree> getTreeNode(@SessionAttribute("user") PermissionUser user){
		Map<String,Object> query=new HashMap<>(16);

		//非GOD用户，不能分配"园所管理权限"
		if (!PermissionUtils.isGod(user)){
			query.put("isGodRes",0);
		}
		List<SysResource> resourceList=sysResourceService.findAllResources(query);
		return parseAllTreeNode(resourceList);
	}

	@GetMapping("/getRoleTreeData/{roleId}")
	@ResponseBody
	public List<Tree> getRoleTreeNode(HttpServletRequest request,@PathVariable("roleId") Integer roleId){
		List<SysResource> resourceList=sysResourceService.findByRoleId(roleId);
		
		return parseAllTreeNode(resourceList);
	}
	private List<Tree> parseAllTreeNode(List<SysResource> resourceList) {
		if(resourceList==null||resourceList.isEmpty()){
			return null;
		}
		return resourceList.stream().map(res -> {
			Tree treeNode = new Tree();
			treeNode.setId(res.getId());
			treeNode.setName(res.getResName());
			treeNode.setpId(res.getResParentId());
			treeNode.setOpen(true);
			if ("首页".equals(res.getResName())) {
				treeNode.setChecked(true);
			} else {
				treeNode.setChecked(false);
			}
			return treeNode;
		}).collect(Collectors.toList());
	}
}
